<template>
  <div>
    <el-divider content-position="center">购买产品</el-divider>
    <div style="text-align: right">
      <el-badge :value="list" class="item">
        <el-button @click="goToBuyCard" size="small">购物车订单</el-button>
      </el-badge>
    </div>
    <el-table
        :data="tableData.filter(data => !search || data.fname.toLowerCase().includes(search.toLowerCase()))"
        style="width: 100%"
        :default-sort="{prop: 'date', order: 'descending'}"
    >
      <el-table-column
          prop="date"
          label="生产日期"
          sortable
          width="180">
      </el-table-column>
      <el-table-column
          prop="fdate"
          label="保质期/天"
          sortable
          width="120">
      </el-table-column>
      <el-table-column
          prop="fname"
          label="名称"
          width="150">
      </el-table-column>
      <el-table-column
          prop="address"
          label="图片">
        <template slot-scope="{row}">
          <el-image
              style="width: 50px; height: 50px"
              :src="row.fimg"
              fit="fill"></el-image>
        </template>
      </el-table-column>
      <el-table-column
          prop="type"
          label="类别"
          width="150"
          :filters="typeList"
          :filter-method="filterTag"
          filter-placement="bottom-end">
        <template slot-scope="scope">
          <el-tag
              :type="scope.row.ftype === '1' ? 'success' : 'warning'"
              disable-transitions>{{ scope.row.ftype === '1' ? '素食' : '饮品' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
          prop="fnum"
          label="数量/件"
          sortable
          width="180">
      </el-table-column>
      <el-table-column
          prop="fprice"
          label="价格/元"
          width="180">
      </el-table-column>
      <el-table-column
          align="right">
        <template slot="header" slot-scope="scope">
          <el-input
              v-model="search"
              size="mini"
              placeholder="输入关键字搜索"/>
        </template>
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" content="购买" placement="top-start">
            <el-button @click="buyThis(scope.row)" type="primary" icon="el-icon-goods" circle></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <el-drawer
        title="购物车列表!"
        :visible.sync="table"
        direction="ltr"
        size="50%">

      <div style="text-align: right;margin-right: 10px">
        <el-button type="primary" @click="saveCart">保存<i class="el-icon-success el-icon--right"></i></el-button>
        <el-button type="danger" @click="goOrder">提交<i class="el-icon-upload el-icon--right"></i></el-button>
      </div>

      <el-table :data="productList">
        <el-table-column property="fname" label="名称" width="150"></el-table-column>
        <el-table-column property="fprice" label="价格 /元" width="100"></el-table-column>
        <el-table-column property="fnum" label="库存"></el-table-column>
        <el-table-column label="数量">
          <template slot-scope="scope">
            <el-input-number size="mini" :min="1" :max="scope.row.fnum" @change="changeNum(scope.row.fprice,$event)"
                             v-model="scope.row.snum"></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="danger" @click="handleRemove(scope.row)" icon="el-icon-delete" circle></el-button>
          </template>
        </el-table-column>
      </el-table>
      <div>
        提示：提交后将自动签署商家售卖协议合同：<a :href="contract.csrc" target="_blank">{{contract.cname}}</a>
      </div>
    </el-drawer>
  </div>
</template>

<script>
export default {
  name: "BuyProductList",
  data() {
    return {
      tableData: [],
      typeList: [],
      list: 0,
      search: '',
      productList: [],
      table: false,
      num: 0,
      contract:{}
    }
  },
  methods: {
    filterTag(value, row) {
      return row.ftype === value;
    },
    buyThis(row) {
      const hasObject = this.productList.some(item => item.fid === row.fid);
      if (hasObject) {
        this.$message.error('您已添加过该商品!');
      } else {
        this.list = this.list + 1
        this.productList.push(row)
        this.$message({
          message: '添加成功!',
          type: 'success'
        });
      }
    },
    goToBuyCard() {
      this.table = !this.table

    },
    changeNum(id, val) {
    },
    handleRemove(row) {
      console.log(row);
      this.list = this.list - 1
      const index = this.productList.findIndex(item => item === row)
      if (index !== -1) {
        this.productList.splice(index, 1)
        row.num = 1
      }
      axios({
        url: `http://localhost:8081/shoppingCart/deleteCart/${row.sid}`,
        method: 'get'
      }).then(res => {
        console.log(res)
        if (res.data.code === 0) {
          this.$message({
            message: "删除成功!",
            type: 'success'
          });
        }
      }).catch(err => {
        console.log(err)
      })
    },
    saveCart() {
      console.log(this.productList)
      let agency = JSON.parse(sessionStorage.getItem("agency"))
      console.log(agency)
      axios({
        method: 'post',
        url: `http://localhost:8081/shoppingCart/saveShoppingCart/${agency.aid}`,
        data: {
          productList: this.productList
        }
      }).then(res => {
        if (res.data.code === 0){
          this.$message({
            message: res.data.msg,
            type: 'success'
          });
          return;
        }
        this.$message.error(res.data.msg);
        this.productList = []
      }).then(err => {
        console.log(err)
      })
    },
    goOrder() {
      let agency = JSON.parse(sessionStorage.getItem("agency"))
      this.$confirm('确认提交吗？', '提交', {
        distinguishCancelAndClose: true,
        confirmButtonText: '保存',
        cancelButtonText: '放弃'
      }).then(() => {
        localStorage.setItem("productList", JSON.stringify(this.productList))
        axios({
          method:'post',
          url:`http://localhost:8081/order/insertOrder/${agency.aid}/${this.contract.cid}`,
          data:{
            productList: this.productList
          }
        }).then(res => {
          console.log(res)
          if (res.data.code === 0){
            this.$message('提交成功，请前往记录页面支付');
            this.$router.push("/orderRecord")
          }else{
            this.$message.error(res.data.msg);
          }
        }).catch(err => {
          console.log(err)
        })
        this.table = !this.table
      }).catch(action => {
        this.$message({
          type: 'info',
          message: action === 'cancel'
              ? '放弃保存并离开页面'
              : '停留在当前页面'
        })
      });
    }
  },
  mounted() {
    axios({
      method: 'get',
      url: 'http://localhost:8081/boss/getFoodList'
    }).then(res => {
      console.log(res)
      this.tableData = res.data.data
      this.tableData.map((v, i) => {
        this.$set(v, 'snum', 1)    //必须要这样赋值
      })
    }).catch(err => {
      console.log(err)
    })
    axios({
      method: 'get',
      url: 'http://localhost:8081/common/getType'
    }).then(res => {
      this.typeList = res.data.data
    }).catch(err => {
      console.log(err)
    })
    let agency = JSON.parse(sessionStorage.getItem("agency"))
    axios({
      method: 'get',
      url: `http://localhost:8081/shoppingCart/getShopping/${agency.aid}`
    }).then(res => {
      console.log(res)

      this.productList = res.data.data
      this.list = this.productList.length
    }).catch(err => {
      console.log(err)
    })
    axios({
      method:'get',
      url:'http://localhost:8081/contract/getMainContract'
    }).then(res=>{
      this.contract = res.data.data
    }).catch(err => {
      console.log(err)
    })
    axios({
      method:'get',
      url:'http://localhost:8081/contract/getMainContract'
    }).then(res=>{
      this.contract = res.data.data
    }).catch(err => {
      console.log(err)
    })
  }
}
</script>

<style scoped>

</style>
